$(document).ready(function(e) {
	//首页小地图
	if($("#map").length>0)
	{
	   // 百度地图API功能
		var mp = new BMap.Map("map");
		mp.centerAndZoom("成都", 15);
		mp.enableScrollWheelZoom();
		// 复杂的自定义覆盖物
		function ComplexCustomOverlay(point, text, mouseoverText){
		  this._point = point;
		  this._text = text;
		  this._overText = mouseoverText;
		}
		ComplexCustomOverlay.prototype = new BMap.Overlay();
		ComplexCustomOverlay.prototype.initialize = function(map){
		  this._map = map;
		  var div = this._div = document.createElement("div");
		  div.style.position = "absolute";
		  div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
		  div.style.backgroundColor = "#EE5D5B";
		  div.style.border = "1px solid #BC3B3A";
		  div.style.color = "white";
		  div.style.height = "18px";
		  div.style.padding = "2px";
		  div.style.lineHeight = "18px";
		  div.style.whiteSpace = "nowrap";
		  div.style.MozUserSelect = "none";
		  div.style.fontSize = "12px"
		  var span = this._span = document.createElement("span");
		  div.appendChild(span);
		  span.appendChild(document.createTextNode(this._text));      
		  var that = this;
	
		  var arrow = this._arrow = document.createElement("div");
		  arrow.style.background = "url(http://map.baidu.com/fwmap/upload/r/map/fwmap/static/house/images/label.png) no-repeat";
		  arrow.style.position = "absolute";
		  arrow.style.width = "11px";
		  arrow.style.height = "10px";
		  arrow.style.top = "22px";
		  arrow.style.left = "10px";
		  arrow.style.overflow = "hidden";
		  div.appendChild(arrow);
		 
		  div.onmouseover = function(){
			this.style.backgroundColor = "#6BADCA";
			this.style.borderColor = "#0000ff";
			this.getElementsByTagName("span")[0].innerHTML = that._overText;
			arrow.style.backgroundPosition = "0px -20px";
		  }
	
		  div.onmouseout = function(){
			this.style.backgroundColor = "#EE5D5B";
			this.style.borderColor = "#BC3B3A";
			this.getElementsByTagName("span")[0].innerHTML = that._text;
			arrow.style.backgroundPosition = "0px 0px";
		  }
	
		  mp.getPanes().labelPane.appendChild(div);
		  
		  return div;
		}
		ComplexCustomOverlay.prototype.draw = function(){
		  var map = this._map;
		  var pixel = map.pointToOverlayPixel(this._point);
		  this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
		  this._div.style.top  = pixel.y - 30 + "px";
		}
		var txt = "天众云合电子商务有限公司", mouseoverTxt = txt + "  地址：守经街6号蔬菜公司旁3栋5单元504" ;
			
		var myCompOverlay = new ComplexCustomOverlay(new BMap.Point(104.068956,30.677629), txt,mouseoverTxt);
	
		mp.addOverlay(myCompOverlay);
		function showInfo(e){
			window.location.href = "games.html?x="+e.point.lng+"&y="+e.point.lat;
		}
		mp.addEventListener("click", showInfo); 
	}
});	


var fx  = {
	buffer : function(obj, cur, target, fnDo, fnEnd, fs){
		if(!fs)fs=6;
		var now={};
		var x=0;
		var v=0;
		
		if(!obj.__last_timer)obj.__last_timer=0;
		var t=new Date().getTime();
		if(t-obj.__last_timer>20)
		{
			fnMove();
			obj.__last_timer=t;
		}
		
		clearInterval(obj.timer);
		obj.timer=setInterval(fnMove, 20);
		function fnMove(){
			v=Math.ceil((100-x)/fs);			
			x+=v;			
			for(var i in cur)
			{
				now[i]=(target[i]-cur[i])*x/100+cur[i];
			}						
			if(fnDo)fnDo.call(obj, now);
			
			if(Math.abs(v)<1 && Math.abs(100-x)<1)
			{
				clearInterval(obj.timer);
				if(fnEnd)fnEnd.call(obj, target);
			}
		}
	},
	
	flex : function(obj, cur, target, fnDo, fnEnd, fs, ms){
		var MAX_SPEED=16;
		
		if(!fs)fs=6;
		if(!ms)ms=0.75;
		var now={};
		var x=0;	//0-100
		
		if(!obj.__flex_v)obj.__flex_v=0;
		
		if(!obj.__last_timer)obj.__last_timer=0;
		var t=new Date().getTime();
		if(t-obj.__last_timer>20)
		{
			fnMove();
			obj.__last_timer=t;
		}
		
		clearInterval(obj.timer);
		obj.timer=setInterval(fnMove, 20);
		
		function fnMove(){
			obj.__flex_v+=(100-x)/fs;
			obj.__flex_v*=ms;

			if(Math.abs(obj.__flex_v)>MAX_SPEED)obj.__flex_v=obj.__flex_v>0?MAX_SPEED:-MAX_SPEED;
			
			x+=obj.__flex_v;
			
			for(var i in cur)
			{
				now[i]=(target[i]-cur[i])*x/100+cur[i];
			}
			
			
			if(fnDo)fnDo.call(obj, now);
			
			if(Math.abs(obj.__flex_v)<1 && Math.abs(100-x)<1)
			{
				clearInterval(obj.timer);
				if(fnEnd)fnEnd.call(obj, target);
				obj.__flex_v=0;
			}
		}
	},
	linear : function (obj, cur, target, fnDo, fnEnd, fs){
		if(!fs)fs=50;
		var now={};
		var x=0;
		var v=0;
		
		if(!obj.__last_timer)obj.__last_timer=0;
		var t=new Date().getTime();
		if(t-obj.__last_timer>20)
		{
			fnMove();
			obj.__last_timer=t;
		}
		
		clearInterval(obj.timer);
		obj.timer=setInterval(fnMove, 20);
		
		v=100/fs;
		function fnMove(){
			x+=v;
			
			for(var i in cur)
			{
				now[i]=(target[i]-cur[i])*x/100+cur[i];
			}
			
			if(fnDo)fnDo.call(obj, now);
			
			if(Math.abs(100-x)<1)
			{
				clearInterval(obj.timer);
				if(fnEnd)fnEnd.call(obj, target);
			}
		}
	},
	
	stop:function (obj){
		clearInterval(obj.timer);
	},
	
	move3 : function(obj, json, fnEnd, fTime, sType){
		var addEnd=fx.addEnd;
		
		fTime||(fTime=1);
		sType||(sType='ease');
		
		setTimeout(function (){
			Utils.setStyle3(obj, 'transition', sprintf('%1s all %2', fTime, sType));
			addEnd(obj, function (){
				Utils.setStyle3(obj, 'transition', 'none');
				if(fnEnd)fnEnd.apply(obj, arguments);
			}, json);
			
			setTimeout(function (){
				if(typeof json=='function')
					json.call(obj);
				else
					Utils.setStyle(obj, json);
			}, 0);
		}, 0);
	
	}

};

//监听css3运动终止
(function (){
	var aListener=[];	//{obj, fn, arg}
	if(!Modernizr.csstransitions)return;	
	if(window.navigator.userAgent.toLowerCase().search('webkit')!=-1)
	{
		document.addEventListener('webkitTransitionEnd', endListrner, false);
	}
	else
	{
		document.addEventListener('transitionend', endListrner, false);
	}
	
	function endListrner(ev)
	{
		var oEvObj=ev.srcElement||ev.target;
		//alert(aListener.length);
		for(var i=0;i<aListener.length;i++)
		{
			if(oEvObj==aListener[i].obj)
			{
				aListener[i].fn.call(aListener[i].obj, aListener[i].arg);
				aListener.remove(aListener[i--]);
			}
		}
	}
	
	fx.addEnd=function (obj, fn, arg)
	{
		if(!obj || !fn)return;
		aListener.push({obj: obj, fn: fn, arg: arg});
	}
})();

var Utils = {
	setStyle :function(obj,json){
		if(obj.length)
			for(var i=0;i<obj.length;i++) Utils.setStyle(obj[i], json);
		else
		{
			if(arguments.length==2)
				for(var i in json) obj.style[i]=json[i];
			else
				obj.style[arguments[1]]=arguments[2];
		}
	},
	setStyle3 : function(obj, name, value){
		obj.style['Webkit'+name.charAt(0).toUpperCase()+name.substring(1)]=value;
		obj.style['Moz'+name.charAt(0).toUpperCase()+name.substring(1)]=value;
		obj.style['ms'+name.charAt(0).toUpperCase()+name.substring(1)]=value;
		obj.style['O'+name.charAt(0).toUpperCase()+name.substring(1)]=value;
		obj.style[name]=value;
	},
	rnd  : function(n,m){
	   return Math.random()*(m-n) + n ;
	}


}

function explode(imgs, div , width , height ){
	var now=0;
	var ready=true;
	var W=width?width:700;
	var H=height?height:400;	
	var $img = imgs;
	var oDiv = div.get(0);
	var next =function(img,key){
		if(key == "pre")
		{
			return (now+$(img).length-1)%$(img).length;
		}
		return (now+1)%$(img).length;
	}
	
	var nextsrc = function(img,key){
		return $(img).eq([next(img,key)]).attr("src");
	}
	
	var nexthref = function(img,key){
		return $(img).eq([next(img,key)]).closest("a").attr("href");
	}
	//获得链接
	var tmpherf = $img.eq(0).closest("a").attr("href");
	if(tmpherf)$(oDiv).attr("data-href",tmpherf);
	//悬浮
	$(oDiv).css("cursor","pointer").click(function(){
		var href = $(this).attr("data-href");
		var str = href.split("|");
		if(str[0]=="1"){
			//球场
			roomShow();
		}
		else{
			//赛事
			window.location.href = href;
		}
	});
	
	return function(event){
		var key = event.data.key;
		if(!ready)return;
		ready=false;
		var R=4;
		var C=7;		
		var cw=W/2;
		var ch=H/2;
		
		oDiv.innerHTML='';
		oDiv.style.background='url('+(nextsrc($img,key))+') center no-repeat';
		//获得链接
		var tmpherf = nexthref($img,key);
		if(tmpherf)$(oDiv).attr("data-href",tmpherf);
		
		var aData=[];
		
		var wait=R*C;
		for(var i=0;i<R;i++){
			for(var j=0,k=0;j<C;j++,k++)
			{
				aData[i]={left: W*j/C, top: H*i/R};
				var oNewDiv=$('<div>');
				oNewDiv.css({
					position: 'absolute',					
					width:Math.ceil(W/C)+'px', 
					height: Math.ceil(H/R)+'px',
					background: 'url('+(nextsrc($img,key))+') '+-aData[i].left+'px '+-aData[i].top+'px no-repeat',					
					left: aData[i].left+'px',
					top: aData[i].top+'px'	
				});

								
				oDiv.appendChild(oNewDiv[0]);
				
				var l=((aData[i].left+W/(2*C))-cw)*Utils.rnd(2,3)+cw-W/(2*C);
				var t=((aData[i].top+H/(2*R))-ch)*Utils.rnd(2,3)+ch-H/(2*R);
				
				setTimeout((function (oNewDiv,l,t){
					return function ()
					{
						fx.buffer(
							oNewDiv,
							{	left: oNewDiv.offsetLeft, 
								top: oNewDiv.offsetTop	,
								opacity: 100,
								x:0,
								y:0,
								z:0,
								scale:1,
								a:0
							},
							{	left: l,
								top: t,
								opacity: 0,
								x:Utils.rnd(-180, 180),
								y:Utils.rnd(-180, 180),
								z:Utils.rnd(-180, 180),
								scale:Utils.rnd(1.5, 3),
								a:1
							},
							function (now){								
								this.style.left=now.left+'px';
								this.style.top=now.top+'px';
								this.style.opacity=now.opacity/100;
								Utils.setStyle3(oNewDiv, 'transform', 'perspective(500px) rotateX('+now.x+'deg) rotateY('+now.y+'deg) rotateZ('+now.z+'deg) scale('+now.scale+')');
							}, function (){
								setTimeout(function (){
									if((window.navigator.userAgent.indexOf("MSIE") >= 0) || $(oDiv).has(oNewDiv).length>0)oDiv.removeChild(oNewDiv);
								}, 200);
								if(--wait==0)
								{
									ready=true;
									now=next($img,key);
								}
							}, 10
						);
					};
				})(oNewDiv[0],l,t), Utils.rnd(0, 200));
			}
		}
	}
}

function itemMove(div){
	var ready =true;
	var now = 0;
	var length = 0;
	var goTo;
	var move = function(){
		if(!ready)return;
		ready=false;
		var oDiv = $("ul",div).get(1);
		var items = $("li",oDiv);
		length = items.length;
		$(oDiv).animate({left:-$(items).eq(goTo()).position().left},function(){
			ready=true;
		});
	}
	return {
		next:function(event){
			goTo = function(){
				return (now+1)%length;
			}
			move();
			now = goTo();
		},
		pre:function(){
			goTo = function(){
				return (now+length-1)%length;
			}
			move();
			now = goTo();
		}
	}
}
$(document).ready(function(e) {
	explode1 = explode($("#imglist img"), $("#imgshow"), 696, 265);
	$("#left").on("click",{key:"pre"}, explode1);
	$("#right").on("click",{key:""}, explode1);
	
	if($("#newslist img").length>0){
		//首页新闻
		explode2 = explode($("#newslist img"), $("#newshow"), 770, 285);
		$("#nleft").on("click",{key:"pre"}, explode2);
		$("#nright").on("click",{key:""}, explode2);
	}
	
	//显示注册框
	$(".btnlogin").click(function(){
		$(".logindiv").fadeIn(1000);
	});
	
	$(".logindiv .btnclose").click(function(){
		$(".logindiv").fadeOut(500);
	});
	
	//显示忘记密码框
	$("#login .btnfogot").click(function(){
		$(".forgotdiv").fadeIn(1000);
	});
	//登录框
	if($(".logindiv2").length>0){
		$(".btnlogin2").click(function(){
			$(".logindiv2").fadeOut(500,function(){
				$(".logindiv").fadeIn(1000);
			});
		});
		$(".logindiv2 .btnclose").click(function(){
			$(".logindiv2").fadeOut(500);
		});
		$(".logindiv2 .btnforgot").click(function(){
			$(".logindiv2").fadeOut(500,function(){
				$(".forgotdiv").fadeIn(1000);
			});
		});
	}
	//忘记密码框
	if($(".forgotdiv").length>0){
		$(".forgotdiv .btnclose").click(function(){
			$(".forgotdiv").fadeOut(500);
		});
	}
	
	if($("#menu-yu").length>0 && $("#menu-lan").length >0){
		//首页场馆滚动
		var moveAction = itemMove($("#gamelist"));
		$("#cdleft").on("click", moveAction.pre);
		$("#cdright").on("click", moveAction.next);
		
		//首页选择运动类型
		$("#menu-yu").click(function(){
			$(this).css("background","url(/img/yu1.png)");
			$("#menu-lan").css("background","url(/img/lang.png)");
			$("#yu").insertAfter("#lan").fadeIn(500,function(){
				$("#lan").fadeOut();
			});
		}).click();
		$("#menu-lan").click(function(){
			$(this).css("background","url(/img/lang1.png)");
			$("#menu-yu").css("background","url(/img/yu.png)");
			$("#lan").insertAfter("#yu").fadeIn(500,function(){
				$("#yu").fadeOut();
			});
		});
	}
	
	//首页场馆预定
	if($("#games #gamelist").length> 0){
		$("#games #gamelist li").delegate("img","click",roomShow);
	}
	
	//场馆预定弹出
	if($("#reservationlist #reservationroom").length>0){
		$("#reservationlist #reservationroom").delegate(".roomitem","click",roomShow);
	}
	if($(".roomdetail").length>0){
		$(".roomdetail .btnclose").on("click",roomHide);
		var toggleFun1 = toggleFun(watchShow,watchHide);
		$(".roomdetail .watch").on("click",toggleFun1);
	}
	
	
	//赛事及报名的图片切换
	if($(".bignews").length>0){
		$(".bignews .min-box div img").click(function(){
			$("<img>").attr("src",this.src).prependTo(".bignews .big");
			$(".bignews .big img").eq(1).fadeOut(2000,function(){
				$(this).remove()
			});
		});
	}
	
	//场馆预定按钮切换
	if($("#reservationlist #reservationroom").length>0){
        var scrollLoad = autoLoad();
		
        
		$("#reservationroom .menu a").click(function(){
			$("#reservationroom .menu a").move_hover_reservationroom_menu_sporttype();
			$(this).add_hover_reservationroom_menu_sporttype();
            $("#reservationroom .roombox .roomlist li").remove("li");
            scrollLoad.reSet('羽毛球');
			scrollLoad.loadItem();
		});
		
		//场馆预定自动加载功能
		/*$(window).scroll(function(){
   			var totalheight = parseFloat($(window).height()) + parseFloat($(window).scrollTop());
			if($(document).height() <= totalheight){
				scrollLoad();
			}
		});*/
		$("#pageMore #more").click(function(){
			scrollLoad.loadItem();
		});
	}
});
//自动加载
function autoLoad(){
	var ready = true;
	var page = 1;
	var seach = '羽毛球';
	return {loadItem : function(){
		if(ready== false) return;
		ready = false;
		$.ajax({
		  url: "/index.php/ativity/loadrooms/"+page,
		  cache: false,
		  type: "POST",
		  data: "seach="+seach,
		  success: function(html){
			$(".roombox .roomlist").append(html);
			ready = true;
			page++;
		  }
		});
	}, reSet : function(s){
		page = 1;
		seach = s;
	}}
}
function toggleFun(fun1,fun2){
	var time = 0;
	return function(){
		if(time%2==0){
			fun1();
		}else{
			fun2();
		}
		time++;
	}
}

function roomShow(){
	$(".roomdetail .comment").fadeOut(500);
	$(".roomdetail .box").hide();
	$(".roomdetail").fadeOut(500,function(){
		$(".roomdetail").fadeIn(1000);
		$(".cover").show();
	});
}
function roomHide(){
	$(".roomdetail .comment").fadeOut(500);
	$(".roomdetail").fadeOut(500);
	$(".roomdetail .box").hide();
	$(".cover").hide();
}

function watchShow(){
	$(".roomdetail .box").show();
	$(".roomdetail .comment").slideDown();
}

function watchHide(){
	$(".roomdetail .comment").slideUp(function(){
		$(".roomdetail .box").hide();
	});
	
}

//jquery拓展
(function($){ 
	$.fn.extend({
		//场馆预定类型切换
		move_hover_reservationroom_menu_sporttype: function(){ 
			return this.each(function(){
				var obj = $(this);
				var re = /\b[^ "]*hover$\b/i;
				var str = obj.attr("class").toString();
				var r = re.exec(str);
				if(r){
					obj.removeClass(r[0]);
					re = /hover/i;
					var r1 = re.exec(r[0]);
					if(r && r1){
						obj.addClass(r[0].substr(0,r1.index));
					}
				}
			});
		},
		add_hover_reservationroom_menu_sporttype:function(){
			return this.each(function(){
				var obj = $(this);
				var re = /(sporttype)[ ]?[*]*\b/i;
				var str = obj.attr("class").toString();
				var r = re.exec(str);
				if(r){
					obj.removeClass(str.substr(r[0].length,str.length));
					obj.addClass(str.substr(r[0].length,str.length)+"hover");
				}
			});
		}
	});
})(jQuery); 